import axios from "axios";
import { createBrowserHistory } from 'history'
import { Toast } from 'antd-mobile'

let history = createBrowserHistory()


//设置拦截器
axios.interceptors.request.use((config) => {
    //携带token请求头
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token');
    return config;
}, (err) => {
    return Promise.reject(err);
})


axios.interceptors.response.use((res) => {
    return res;
}, (err) => {
    //处理错误状态码
    if (err.response.status == 401) {
        Toast.show({ content: "身份验证失败，登录过期" })
        //删除token
        localStorage.removeItem('token');
        //跳转到登录页
        history.push('/login');
        history.go();//刷新作用（刷新路由）

    } else if (err.response.status == 404) {
        Toast.show({ content: "访问路径有误！！！" })
    } else if (err.response.status == 500) {
        Toast.show({ content: "服务器内部错误！！！" })
    }
    return Promise.reject(err);
})

export default axios;